package com.example.cadmin.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.cadmin.entity.FileAttribute;
import com.example.cadmin.service.FileAttributeService;
import com.example.cadmin.utils.ResponseModel;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Map;


/**
 * <p>
 * 档案属性 前端控制器
 * </p>
 *
 * @author  zzsoft 
 * @since 2023-02-13
 */
@Controller
@RequestMapping("/file/attribute")
public class FileAttributeController {

    @Resource
    public FileAttributeService fileAttributeService;

    @GetMapping("/index")
    public String index(){
        return "FileAttribute/attribute-list";
    }

    @ResponseBody
    @GetMapping("/list")
    public Map<String,Object> attributeList(@RequestParam(value = "fileAttributeName",required = false) String fileAttributeName,
                                       @RequestParam(value = "page") int page,
                                       @RequestParam(value = "limit") int limit){
        return fileAttributeService.attributeList(fileAttributeName,page,limit);
    }


    @GetMapping("/add")
    @PreAuthorize("hasAnyAuthority('attribute:add')")
    public ModelAndView attributeAdd(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("FileAttribute/attribute-add");
        return modelAndView;
    }

    @PostMapping("/save")
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('attribute:add')")
    public ResponseModel attributeSave(@RequestBody JSONObject data) {
        if (StrUtil.isEmpty(data.getStr("fileAttributeName"))) {
            return ResponseModel.fail("档案属性名为空");
        }
        return fileAttributeService.attributeSave(data);
    }


    @GetMapping("edit")
    @PreAuthorize("hasAnyAuthority('attribute:edit')")
    public ModelAndView edit(@RequestParam int attributeId){
        Map<String,Object> fileAttribute = fileAttributeService.getMap(new QueryWrapper<FileAttribute>().eq("id",attributeId));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("FileAttribute/attribute-edit");
        modelAndView.addAllObjects(fileAttribute);
        return modelAndView;
    }

    @PostMapping("editInfo")
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('attribute:edit')")
    public ResponseModel editInfo(@RequestBody JSONObject data){
        return fileAttributeService.editInfo(data);
    }


    @DeleteMapping("/remove/{attributeId}")
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('attribute:del')")
    public ResponseModel remove(@PathVariable("attributeId") String attributeId){
        return fileAttributeService.remove(attributeId);
    }
}
